﻿<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增供应商</title>
    <!-- 引入 Element Plus CSS -->
    <!-- 引入 Vue 和 Element Plus JS -->
    <script src="~/lib/vue/vue.global.min.js"></script>
    <script src="~/lib/element-plus/index.full.js"></script>
    <link href="~/lib/element-plus/index.min.css" rel="stylesheet" />
    <link href="~/lib/element-plus/index.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        .container {
            width: 95%;
            margin: 20px auto;
        }

        .form-group {
            margin-bottom: 20px;
            /* 背景板样式 */
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .form-item {
            margin-bottom: 16px;
        }

        .note-input {
            height: 100px;
        }

        .upload-area {
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 基础信息 -->
        <div class="form-group">
            <h3>基础信息</h3>
            <el-form label-width="120px">
                <!-- 第一行：客户编码、客户名称 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="供应商编码" required class="form-item">
                            <el-input placeholder="自动获取系统编号" v-model="formData.supplier_code" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="供应商名称" required class="form-item">
                            <el-input v-model="formData.supplier_name" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第二行：所属行业、客户来源 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="所属行业" class="form-item">
                            <!-- v-model 绑定表单中“所属行业”的选中值 -->
                            <el-select v-model="formData.indInd" placeholder="请选择">
                                <!-- 循环渲染从后端获取的字典选项 -->
                                <el-option v-for="item in industryOptions"
                                           :key="item.value"       
                                           :label="item.dictLabel"
                                           :value="item.dictValue"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="供应商分类" class="form-item">
                            <!-- v-model 绑定表单中“供应商分类”的选中值 -->
                            <el-select v-model="formData.supplier_classification" placeholder="请选择">
                                <!-- 循环渲染从后端获取的字典选项 -->
                                <el-option v-for="item in SuppOptions"
                                           :key="item.value"
                                           :label="item.dictLabel"
                                           :value="item.dictValue"></el-option>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第三行：联系人、联系电话 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="联系人" class="form-item">
                            <el-input v-model="formData.contact_person" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" class="form-item">
                            <el-input v-model="formData.contact_phone_number" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第四行：电子邮箱、销售部门 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="电子邮箱" class="form-item">
                            <el-input v-model="formData.email_address" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="进货部门" class="form-item">
                            <el-select placeholder="请选择">
                                <el-option label="销售一部" value="销售一部"></el-option>
                                <el-option label="销售二部" value="销售二部"></el-option>
                                <el-option label="销售三部" value="销售三部"></el-option>
                                <el-option label="大客户部" value="大客户部"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第五行：销售负责人、状态 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="进货负责人" class="form-item">
                            <el-select placeholder="请选择">
                                <el-option label="张三" value="张三"></el-option>
                                <el-option label="李四" value="李四"></el-option>
                                <el-option label="王五" value="王五"></el-option>
                                <el-option label="赵六" value="赵六"></el-option>
                                <el-option label="钱七" value="钱七"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" class="form-item">
                            <el-radio v-model="formData.status" label=1>启用</el-radio>
                            <el-radio v-model="formData.status" label=2>停用</el-radio>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第六行：客户地址 -->
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="供应商地址" class="form-item">
                            <el-input v-model="formData.suppliers_address" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第七行：备注 -->
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" class="form-item">
                            <el-input v-model="formData.note" type="textarea" placeholder="请输入" class="note-input"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 财务信息 -->
        <div class="form-group">
            <h3>财务信息</h3>
            <el-form label-width="120px">
                <!-- 第一行：账户名称、纳税人识别号 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="账户名称" class="form-item">
                            <el-input v-model="formData.account_name" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="纳税人识别号" class="form-item">
                            <el-input v-model="formData.taxid" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第二行：银行账户、开户银行 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="银行账户" class="form-item">
                            <el-input v-model="formData.bank_account" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开户银行" class="form-item">
                            <el-input v-model="formData.opening_bank" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第三行：开户行地址 -->
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="开户行地址" class="form-item">
                            <el-input v-model="formData.bkaddr" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 上传附件 -->
        <div class="form-group">
            <h3>上传附件</h3>
            <div class="upload-area">
                <el-upload action="/api/Supplier/UploadFile"
                    :file-list.sync="fileList"
                    :on-success="handleUploadSuccess"
                    :before-upload="beforeUpload"
                    :limit="3"
                >
                    <el-button type="primary">上传</el-button>
                </el-upload>
                <div class="tip">您可以上传 doc、pdf、rar 等格式的文件，单个文件上传最大 200MB。</div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div style="margin-top: 20px;">
            <el-button v-on:click="goBack">关闭</el-button>
            <el-button type="primary" v-on:click="saveAndAdd">保存并新增</el-button>
            <el-button type="primary" v-on:click="save">保存</el-button>
        </div>
    </div>

    <script>
        const { createApp, ref,reactive, onMounted } = Vue; // 引入 Vue 核心API
        const app = createApp({
            setup() {
                // 定义响应式变量
                const fileList = ref([]);           // 上传文件列表
                

                const formData = reactive({
                    supplier_code:'GYS202510190001',//供应商编码
                    indInd: '',//所属行业
                    supplier_classification: '',//供应商分类
                    supplier_name:'',//供应商名称
                    contact_person:'',//联系人
                    contact_phone_number:'',//联系电话
                    email_address:'',//电子邮箱
                    purchasing_department_id: 1,//进货部门id
                    purchasing_manager_id: 1,//进货负责人id
                    suppliers_address:'',//供应商地址
                    account_name:'',//账号名称
                    taxid:'',//纳税人识别号
                    bank_account:'',//银行账户
                    opening_bank:'',//开户银行
                    bkaddr:'',//开户银行地址
                    status: '1',//状态
                    note:'',//备注
                    create_by:'admin',//创建人
                    annex_code: ''
                });
                console.log(formData);

                const industryOptions = ref([]);    // 所属行业的字典选项

                // 获取“所属行业”字典数据
                const getIndustryDict = async () => {
                    try {
                      // 调用后端接口：/api/Dict/datas/Industry（DictTypeCode 为 Industry）
                      const response = await axios.get('/api/Dict/datas/Industry');
                      console.log(response.data)
                      // 格式化后端返回的字典数据（映射为 Select 组件需要的 label/value 格式）
                      industryOptions.value = response.data;
                      console.log(industryOptions.value)
                    } catch (error) {
                      console.error('获取所属行业字典失败：', error);
                      ElementPlus.ElMessage.error('获取所属行业数据失败，请稍后再试'); // 错误提示
                    }
                };
                
                const SuppOptions = ref([]);//供应商分类数据字典选项
                // 获取“供应商分类”字典数据
                const getSupplierClassificationDict = async () => {
                    try {
                      // 调用后端接口：/api/Dict/datas/Industry（DictTypeCode 为 Industry）
                      const response = await axios.get('/api/Dict/datas/SupplierClassification');
                      console.log(response.data)
                      // 格式化后端返回的字典数据（映射为 Select 组件需要的 label/value 格式）
                      SuppOptions.value = response.data;
                      console.log(SuppOptions.value)
                    } catch (error) {
                      console.error('获取供应商分类字典失败：', error);
                      ElementPlus.ElMessage.error('获取供应商分类数据失败，请稍后再试'); // 错误提示
                    }
                };


                // 商品新增页面的Vue逻辑中，新增获取供应商编号的方法 
                const getSupplierNumber = async () => {
                    try {
                        console.log("获取的供应商编号：", formData.supplier_code);
                        // 调用供应商编号生成接口（rule_id=11 对应供应商的编号规则）
                        const res = await axios.post("/NumberingRule/GenerateBusinessNumber?rule_id=11");

                        if (res.data.success) {
                            // 将生成的供应商编号赋值给商品模块中关联供应商的字段（如 supplierCode）
                            formData.supplier_code = res.data.businessNumber;
                            console.log("获取的供应商编号：", formData.supplier_code);
                            // 关闭所有错误提示
                            ElementPlus.ElMessage.closeAll();
                        } else {
                          ElementPlus.ElMessage.error(res.data.message);
                        }

                    } catch (err) {
                        console.error("获取供应商编号失败：", err);
                        ElementPlus.ElMessage.error("获取供应商编号失败，请稍后再试");
                    }
                };

                
                
                // 组件挂载时执行：获取字典数据
                onMounted(() => {
                    getIndustryDict(); // 页面加载完成后，立即请求字典数据
                    getSupplierClassificationDict();
                    getSupplierNumber();
                });
                
                // 页面方法（原有逻辑，保持不变）
                const goBack = () => { window.history.back(); };
                const saveAndAdd = () => { alert('保存成功，即将跳转到新增页面'); };

                //添加
                const save = async () => {
                    try {
                        // 1. 创建FormData对象（用于提交表单+文件）
                        const formData2 = new FormData();

                        // 2. 添加表单字段（与后端接收模型字段对应）
                        formData2.append("supplier_code", formData.supplier_code);
                        formData2.append("supplier_name", formData.supplier_name);
                        formData2.append("indInd", formData.indInd); // 所属行业（已修正字段名）
                        formData2.append("supplier_classification", formData.supplier_classification);
                        formData2.append("contact_person", formData.contact_person);
                        formData2.append("contact_phone_number", formData.contact_phone_number);
                        formData2.append("email_address", formData.email_address);
                        formData2.append("purchasing_department_id", formData.purchasing_department_id);
                        formData2.append("purchasing_manager_id", formData.purchasing_manager_id);
                        formData2.append("suppliers_address", formData.suppliers_address);
                        formData2.append("account_name", formData.account_name);
                        formData2.append("taxid", formData.taxid);
                        formData2.append("bank_account", formData.bank_account);
                        formData2.append("opening_bank", formData.opening_bank);
                        formData2.append("bkaddr", formData.bkaddr);
                        formData2.append("status", formData.status);
                        formData2.append("note", formData.note);
                        formData2.append("create_by", formData.create_by);
                        formData2.append("annex_code", formData.annex_code); // 关键：传递附件编号

                                
                        // 4. 提交请求（ contentType: false 必加，让浏览器自动处理FormData格式）
                        const response = await axios.post("/Supplier/AddSupplier", formData2, {
                            headers: { "Content-Type": "multipart/form-data" }
                        });

                        // 5. 处理响应
                        if (response.data.success) {
                            ElementPlus.ElMessage.success("添加供应商成功");
                            goBack(); // 返回列表页
                        } else {
                            ElementPlus.ElMessage.error("添加失败：" + response.data.message);
                        }
                    } catch (error) {
                      console.error("提交失败：", error);
                      ElementPlus.ElMessage.error("网络错误，请稍后再试");
                    }
                };

                    // 1. 文件上传前校验（格式+大小）
                const beforeUpload = (file) => {
                    // 允许的文件格式
                    const allowedTypes = ['application/msword', 'application/pdf', 'application/x-rar-compressed'];
                    // 单个文件最大200MB（转换为字节）
                    const maxSize = 200 * 1024 * 1024;
                
                    // 格式校验
                    if (!allowedTypes.includes(file.type)) {
                        ElementPlus.ElMessage.error('仅支持 doc、pdf、rar 格式文件');
                        return false;
                    }
                    // 大小校验
                    if (file.size > maxSize) {
                        ElementPlus.ElMessage.error('单个文件最大不能超过200MB');
                        return false;
                    }
                    return true;
                };
                
                // 2. 上传成功后：获取附件编号（后端返回）并赋值给formData
                const handleUploadSuccess = (response) => {
                    if (response.success) {
                        // 后端需返回“annex_code”（附件编号，关联SysOrgPublicAttachments表）
                        formData.annex_code = response.data.annex_code;
                        ElementPlus.ElMessage.success('附件上传成功');
                    } else {
                        ElementPlus.ElMessage.error('附件上传失败：' + response.message);
                    }
                };
                
                // 返回需要在模板中使用的变量/方法
                return {
                    fileList,
                    industryOptions,
                    goBack,
                    saveAndAdd,
                    save,
                    SuppOptions,
                    formData,
                    beforeUpload,
                    handleUploadSuccess 

                };
            }
        });
        app.use(ElementPlus); // 注册 Element Plus 组件
        app.mount('.container'); // 挂载到页面容器
    </script>
</body>

</html>